package com.lzp.controller;

import com.lzp.common.Result;
import com.lzp.common.batch.WeChatFieldSetMapper;
import com.lzp.query.WechatBillPageQuery;
import com.lzp.entity.WechatBill;
import com.lzp.server.AliPayServer;
import com.lzp.server.WechatBillServer;
import com.lzp.service.WechatBillService;
import com.lzp.utils.FileUtils;
import com.lzp.common.batch.AliPayFieldSetMapper;
import com.lzp.common.batch.BillExcelReader;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.batch.core.step.tasklet.TaskletStep;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.annotation.MultipartConfig;
import java.io.*;
import java.net.URL;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author lzp
 * @version 1.0.0
 * @date 2022/4/27 17:30:26
 * @apiNote 微信账单控制层
 */
@Api
@RestController
@MultipartConfig
@RequestMapping
public class WechatBillController {
    //todo 由server触发批处理,获取对应的读取writer,经过processor中间处理后统一存入数据库,这里只提供查询相关的接口,返回格式化json展示

    @Resource
    JobLauncher jobLauncher;
    @Autowired
    WechatBillService wechatBillService;
    @Resource
    WeChatFieldSetMapper weChatFieldSetMapper;
    @Resource
    AliPayFieldSetMapper aliPayFieldSetMapper;
    @Resource
    JobBuilderFactory jobBuilderFactory;
    @Resource
    StepBuilderFactory stepBuilderFactory;

    @GetMapping("selectList")
    @ApiOperation("条件查询账单记录")
    public Result<List<WechatBill>> selectList(WechatBillPageQuery wechatBillPageQuery) {
        List<WechatBill> list = wechatBillService.selectList(wechatBillPageQuery);
        return Result.success(list);
    }

    @GetMapping("startBatch")
    @ApiOperation("主动触发批处理")
    public String startBatch() throws Exception {
        URL wechatResource = this.getClass().getResource("/bill/wechat");
        String path = wechatResource.getPath();
        File file1 = new File(path);
        List<String> directoryFile = FileUtils.getDirectoryFile(file1);
        BillExcelReader<WechatBill> instance = BillExcelReader.getInstance(weChatFieldSetMapper, WechatBillServer.WECHAT_BILL_LINE);
        instance.setLinesToSkip(17);
        for (String filePath : directoryFile) {
            File file = new File(filePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamResource inputStreamResource = new InputStreamResource(fileInputStream);
            instance.setResource(inputStreamResource);
            TaskletStep step = stepBuilderFactory.get("step")
                    .<WechatBill, WechatBill>chunk(10)
                    .reader(instance)
                    .writer(items -> {
                        wechatBillService.saveBatch((Collection<WechatBill>) items);
                    })
                    .build();
            Job myJob = jobBuilderFactory.get("job").start(step).build();
            try {

                jobLauncher.run(myJob, new JobParametersBuilder().addDate("date", new Date()).toJobParameters());
            } catch (JobExecutionAlreadyRunningException e) {
                e.printStackTrace();
            } catch (JobRestartException e) {
                e.printStackTrace();
            } catch (JobInstanceAlreadyCompleteException e) {
                e.printStackTrace();
            } catch (JobParametersInvalidException e) {
                e.printStackTrace();
            }
        }
        File alipayDir = new File(this.getClass().getResource("/bill/alipay").getPath());
        BillExcelReader<WechatBill> alipayInstance = BillExcelReader.getInstance(aliPayFieldSetMapper, AliPayServer.ALIPAY_BILL_LINE);
        List<String> directoryFile1 = FileUtils.getDirectoryFile(alipayDir);
        alipayInstance.setLinesToSkip(2);
        alipayInstance.setEncoding("gbk");
        for (String filePath : directoryFile1) {
            File file = new File(filePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamResource inputStreamResource = new InputStreamResource(fileInputStream);
            alipayInstance.setResource(inputStreamResource);

            TaskletStep step = stepBuilderFactory.get("step")
                    .<WechatBill, WechatBill>chunk(10)
                    .reader(alipayInstance)
                    .writer(items -> {
                        wechatBillService.saveBatch((Collection<WechatBill>) items);
                    })
                    .build();
            Job myJob = jobBuilderFactory.get("job").start(step).build();
            try {

                jobLauncher.run(myJob, new JobParametersBuilder().addDate("date", new Date()).toJobParameters());
            } catch (JobExecutionAlreadyRunningException e) {
                e.printStackTrace();
            } catch (JobRestartException e) {
                e.printStackTrace();
            } catch (JobInstanceAlreadyCompleteException e) {
                e.printStackTrace();
            } catch (JobParametersInvalidException e) {
                e.printStackTrace();
            }
        }


        return "success";
    }
}
